/*
This software is distributed under the Simplified BSD License:

Copyright (c) 2008, Chris Venter <chris.venter@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
    	this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
    	this list of conditions and the following disclaimer in the documentation 
    	and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
DAMAGE.
*/
#include "logging.h"

//#define GENERIK_SILENCE

namespace generik
{
	
	namespace logging
	{
	
		static init& get_init()
		{
			static generik::tracing::init _init;
			return _init;
		}

		std::ostream* get_stream()
		{
		#ifndef GENERIK_SILENCE
			return get_init().get_stream();
		#else
			return 0;
		#endif
		}

		std::ostream* set_stream(std::ostream* stream_in)
		{
		#ifndef GENERIK_SILENCE
			return get_init().set_stream(stream_in);
		#else
			return 0;
		#endif
		}

		std::ostream* set_stream(const std::string& filename)
		{
		#ifndef GENERIK_SILENCE
			std::ofstream* logfile = new std::ofstream(filename.c_str());
			if (!logfile->is_open())
			{
				//std::clog<<"could not open logfile ["<<filename<<"] for writing"<<std::endl;
				delete logfile;
				logfile = 0;
			}
			return set_stream(logfile);
		#else
			return 0;
		#endif
		}
		
	}
}


namespace generik
{
	
	namespace tracing
	{

		init::init()
		: _stream(0)
		{
		#ifndef GENERIK_SILENCE
			GENERIK_INIT_TRACE("initialising...");
			char* trace_stream_name = getenv("GENERIK_TRACE_STREAM");
			if (trace_stream_name)
			{
				GENERIK_INIT_TRACE("using GENERIK_TRACE_STREAM: "<<trace_stream_name);
				set_stream(trace_stream_name);
			}
			else
			{
				GENERIK_INIT_TRACE("using std::clog");
				set_stream(&std::clog);
			}
			GENERIK_INIT_TRACE("...done");
		#endif
		}
		
		std::ostream* init::get_stream()
		{
		#ifndef GENERIK_SILENCE
			return _stream;
		#else
			return 0;
		#endif
		}
		
		std::ostream* init::set_stream(std::ostream* stream_in)
		{
		#ifndef GENERIK_SILENCE
			if (stream_in)
			{
				std::ostream* prev = _stream;
				GENERIK_INIT_TRACE("setting stream to pointer "<<(void*)stream_in);
				_stream = stream_in;
				return prev;
			}
		#endif
			return 0;
		}
		
		void init::set_stream(const std::string& filename)
		{
		#ifndef GENERIK_SILENCE
			GENERIK_INIT_TRACE("setting stream to file "<<filename);
			std::ofstream* file = new std::ofstream(filename.c_str());
			if (!file->good())
			{
				GENERIK_INIT_TRACE("could not open tracing stream: "<<filename);
				delete file;
			}
			else
			{
				_stream = file;
			}
		#endif
		}
		
	}
}

namespace generik
{
	namespace tracing
	{
		
#ifndef GENERIK_SILENCE
		
		std::string itoa(int value_in)
		{
			std::stringstream string;
			string<<value_in<<" ";
			return string.str();
		}
		std::string at()
		{
			return itoa(clock());
		}
		
		int pid()
		{
			return getpid();
		}
		int tid()
		{
			pthread_t tid = pthread_self();
			unsigned int pself = *((unsigned int*)&tid);
			return pself;
		}
		
		std::string mem()
		{
#ifdef GENERIK_TRACE_VMEM
			// read the virtual memory as reported by /proc
			std::stringstream s;
			s<<"/proc/"<<getpid()<<"/stat";
			std::ifstream f(s.str().c_str());
			std::string vsize;
			// it is the 23rd entry in the output of /proc/*/stat
			for (int i = 0; i < 23; ++i) f>>vsize;
			s.str("");
			s<<"["<<vsize<<"]";
			return s.str();
#else
			return "*";
#endif
		}

		void output(char pre, const std::string& message_in)
		{
			std::stringstream ss;
			ss<<pre<<" "<<pid()<<" "<<tid()<<" "<<mem()<<" "<<message_in<<"\n";
			std::ostream* stream_ = get_stream();
			(*stream_)<<ss.str()<<std::flush;
		}
#endif
		
		void output(const std::string& message_in)
		{
		#ifndef GENERIK_SILENCE
			output('~', message_in);
		#endif
		}
		
		void tracer::msg(char pre, const std::string& message_in)
		{
		#ifndef GENERIK_SILENCE
			if (_active)
			{
				output(pre, message_in);
			}
		#endif
		}
		
		void tracer::trace(const std::string& message_in)
		{
		#ifndef GENERIK_SILENCE
			msg(':', "\t" + message_in);
		#endif
		}
		void tracer::log(const std::string& message_in)
		{
		#ifndef GENERIK_SILENCE
			msg('#', "\t"+ message_in);
		#endif
		}
		void tracer::error(const std::string& message_in)
		{
		#ifndef GENERIK_SILENCE
			msg('E', "\t" + message_in);
		#endif
		}
		void tracer::assert_(const std::string& evalstr_in, bool)
		{
		#ifndef GENERIK_SILENCE
			msg('%', "\t" + evalstr_in);
		#endif
		}
		void tracer::print(const std::string& message_in)
		{
		#ifndef GENERIK_SILENCE
			output('~', message_in);
		#endif
		}
		bool tracer::active() const
		{
		#ifndef GENERIK_SILENCE
			return _active;
		#else
			return false;
		#endif
		}
		
		tracer::tracer()
		#ifndef GENERIK_SILENCE
		: _active(false)
		#endif
		{}
		
		tracer::tracer(const std::string& function_in)
		#ifndef GENERIK_SILENCE
		: _active(true)
		, _function(function_in)
		, _start0(clock())
		#endif
		{
		#ifndef GENERIK_SILENCE
			msg('+', _function);
		#endif
		}
		
		tracer::~tracer()
		{
		#ifndef GENERIK_SILENCE
#ifdef GENERIK_TRACE_TIME
			clock_t stop = clock();
			double delta = (double)(stop - _start0) / CLOCKS_PER_SEC;
			std::stringstream ss;
			ss<<" ~"<<delta<<" ("<<stop-_start0<<")";
			msg('-', _function + ss.str());
#else
			msg('-', _function);
#endif
		#endif
		}
		
	}
}

